<template>
  <view>
    <view v-if="outPayH5" class="outPayH5">
      <web-view
        class="outPayH5"
        v-if="1"
        :src="outPayH5Url"
        @onPostMessage="handleWebviewPostMessage"
        @message="handleWebviewPostMessage"
      ></web-view>
    </view>
    <view
      v-if="!outPayH5 && (shenheStatus != 1 || !shenheAliStatus)"
      class="pay-settle-page"
    >
      <view class="page-header">
        <view class="pay-rest-time" v-if="!activity_cut_price_order_id">
          {{ $t("pay.time")
          }}<text style="margin-left: 10rpx">{{ `${minute}:${second}` }}</text>
        </view>
        <view class="pay-price">
          <text>￥</text>
          <text v-if="!pay_price">0.00</text>
          <template v-else>
            <text>{{ pay_price | priceBeforeZero }}</text>
            <text>{{ pay_price | priceAfterZero }}</text>
          </template>
        </view>
      </view>
      <view class="page-body">
        <view class="recommend-pay" v-if="userAccountMoney && useCombinePay">
          <view class="recommend-pay-name">
            <view>{{ $t("pay.recommend") }}</view>
          </view>
          <view class="recommend-pay-detail">
            <view class="select">
              <view class="pay-detail flex-y-center">
                <text
                  class="iconfont icon-consumption-fill"
                  style="font-size: 54rpx; color: #fa9c0e"
                ></text>
                <view class="pay-word">
                  <text>{{ $t("common.payMethod3") }}</text>
                  <text style="margin-left: 14rpx"
                    >（{{ $t("coupon.price2") }}￥{{ userAccountMoney }}）</text
                  >
                </view>
              </view>
              <view class="is-select" @click="combinePay()">
                <image
                  v-if="isCombinePay"
                  :src="asyncImgs.images.choosed_red_icon"
                  mode="aspectFit"
                />
                <view v-else></view>
              </view>
            </view>
          </view>
        </view>
        <view class="pay-way-list">
          <view class="flex-y-center flex-x-sb">
            <view class="left">{{ $t("pay.other") }}</view>
            <view v-show="realPrice > 0 && isCombinePay" class="right"
              >{{ $t("pay.need") }}
              <text class="red">￥{{ realPrice }}</text></view
            >
          </view>
          <view
            class="pay-way-item"
            v-for="(item, index) in pay_type_list"
            :key="index"
            @click="handlePayTypeItem(item)"
          >
            <view class="pay-type">
              <!-- 微信支付 -->
              <i
                v-if="item.payment == 1 || item.payment == 101"
                class="icon-weixinzhifu iconfont"
                style="color: #09bb07; font-size: 54rpx"
              ></i>
              <!-- 货到付款 -->
              <i
                v-else-if="item.payment == 2"
                class="icon-yinhangka1 iconfont"
                style="color: #34cb9b; font-size: 54rpx"
              ></i>
              <!-- 线上支付 -->
              <i
                v-else-if="item.payment == 5"
                class="icon-money-rmb iconfont"
                style="color: #ec9d38; font-size: 52rpx; margin-right: 2rpx"
              ></i>
              <!-- 支付宝 -->
              <i
                v-else-if="item.payment == 4 || item.payment == 401"
                class="icon-zhifubao1 iconfont"
                style="color: #5a9ef7; font-size: 54rpx"
              ></i>
              <!-- adapay快捷 -->
              <i
                v-else-if="item.payment == 1001"
                class="icon-money-rmb iconfont"
                style="color: #ec9d38; font-size: 54rpx"
              ></i>
              <i
                v-else-if="item.payment == 7"
                class="icon-trust-fill iconfont"
                style="color: #f0250e; font-size: 54rpx"
              ></i>
              <i
                v-else-if="item.payment == 11"
                class="icon-money-currency-converter-fill iconfont"
                style="color: #8a2cd1; font-size: 54rpx"
              ></i>
              <view v-else-if="item.payment == 13">
                <image
                  :src="asyncImgs.images.yunst_pay_icon"
                  style="width: 52rpx; height: 52rpx; margin-right: 8rpx"
                ></image>
              </view>
              <i
                v-else-if="item.payment == 12"
                class="icon-money-yuefu iconfont"
                style="color: #8a2cd1; font-size: 54rpx"
              ></i>

              <text>{{ item.name }}</text>
              <text style="color: #888888" v-if="item.payment == 12"
                >（可用额度{{ obj }})</text
              >
            </view>
            <view class="is-select">
              <image
                v-if="payment == item.payment"
                :src="asyncImgs.images.choosed_red_icon"
                mode="aspectFit"
              />
              <view v-else></view>
            </view>
          </view>
        </view>

        <!-- #ifdef H5 -->
        <view ref="html" id="aliFrom" v-html="html" v-show="false"></view>
        <!-- #endif -->
      </view>
      <view class="page-foot">
        <view class="pay-btn" @click="gotoPay"
          >{{ $t("pay.pay") }}￥{{ realPrice || pay_price }}</view
        >
      </view>
      <view class="payResBox" v-if="showPayResult">
        <view class="payRes">
          <button type="primary" @click="payBtn">已完成付款</button>
          <button @click="payBtn" style="margin-top: 20rpx">未支付</button>
        </view>
      </view>

      <view class="virtualPop" v-if="asyncImgs && showVirtualPop">
        <view class="virtualPopBox">
          <view class="hd"
            ><image mode="widthFix" :src="asyncImgs.coupon.virtual_head"></image
          ></view>

          <view class="conBox">
            <scroll-view class="scroll" scroll-y>
              <view class="cardItem" v-for="item of verify_card" :key="item.id">
                <view class="img">
                  <image :src="item.pic_url" mode="aspectFill"></image>
                </view>
                <view class="txt">
                  <view class="con">
                    <view class="name">{{ item.name }}</view>
                    <view class="num">数量：{{ item.num }}</view>
                  </view>

                  <!-- <view
                v-if="status === 3"
                class="btn"
                @click="handleClick(item)"
                >{{ getCouponText(parseInt(item.type)) }}</view
              > -->
                </view>
              </view>

              <view
                class="couponItem"
                v-for="item of coupon_card"
                :key="item.id"
              >
                <view class="line">
                  <view></view>
                  <view></view>
                </view>

                <view class="let">
                  <view class="title">{{ item.name }}</view>
                  <view class="time"
                    >{{ item.begin_time }}-{{ item.end_time }}</view
                  >
                </view>
                <view class="rig">
                  <view
                    :class="['price', item.discount_type === 1 ? 's2' : 's1']"
                    >{{
                      item.discount_type === 1 ? item.discount : item.sub_price
                    }}</view
                  >
                  <view class="text">满{{ item.min_price }}可用</view>
                </view>
              </view>
            </scroll-view>
            <view class="btn" @click="goCardList"><view>开心收下</view></view>
          </view>
        </view>
      </view>
      <u-popup
        :mask-close-able="false"
        v-model="showBackApp"
        :border-radius="20"
        mode="center"
      >
        <view class="back-app-popup-box">
          <view
            class="u-font-32 font-w-600 u-text-center u-p-t-20 u-p-b-20 u-m-b-30"
          >
            支付成功
          </view>
          <view class="flex-x-center">
            <!-- #ifdef MP-WEIXIN -->
            <button open-type="launchApp" class="button-initial back-app">
              返回APP
            </button>
            <!-- #endif -->
            <!-- #ifdef MP-ALIPAY -->
            <!-- <button open-type="launchApp" class="button-initial back-app">
            返回APP
          </button> -->
            <!-- #endif -->
          </view>
        </view>
      </u-popup>
    </view>
    <Shenhe v-else-if="shenheStatus == 1"></Shenhe>
  </view>
</template>

<script>
import Shenhe from "@/components/shenhe/shenhe";
import orderPay from "../../common/orderPay.js";
import adopt_order from "@/api/livestockAdoption/adopt_order.js";
import { passportCode } from "@/api/login";

export default {
  components: { Shenhe },
  data() {
    return {
      pay_price: 0, //账单支付金额
      pay_type_list: [],
      countDown: 15 * 60 * 1000, // 倒计时-   单位：毫秒
      timer: null,
      hour: "00",
      minute: "00",
      second: "00",
      payment: 1, // 1:微信，2:货到付款，3:余额，4:支付宝
      outPayH5: false,
      outPayH5Url: "",
      imgs: [],
      payData: {},
      backUrl: "",
      userAccountMoney: 0, // 账户余额
      useCombinePay: 0, // 是否开启组合支付
      isCombinePay: 0, // 是否使用组合支付
      realPrice: 0, //支付金额
      isFacePay: false,
      isShowViewPay: true, //是否显示除余额外 其他支付方式
      // h5展示支付结果的弹窗
      showPayResult: false,
      showVirtualPop: false,
      adopt_pay: false,
      verify_card: [],
      coupon_card: [],
      is_pt: false,
      activity_cut_price_order_id: 0,
      app_user_code: "", //app跳转小程序登录key，一次性
      app_alipay_mini_id: "",
      app_wx_mini_id: "", //app跳转小程序的id
      app_wx_mini_type: 0, //app跳转小程序的type类型
      createDate: "",
      showBackApp: false,
      obj: 0,

      ali: {
        ali_requireOrder: "",
        ali_sourceId: "",
        ali_sceneId: ""
      },
      html: ""
    };
  },
  computed: {
    getCouponText() {
      return (type) => {
        let str;

        switch (type) {
          case 1:
            str = this.$t("writeOff.toCancle");
            break;

          case 2:
            str = this.$t("coupon.pickUpGoods");
            break;

          case 3:
            str = this.$t("coupon.recharge");
            break;

          case 4:
            str = this.$t("coupon.see");
            break;

          case 5:
            str = this.$t("coupon.watchOnline");
            break;
        }

        return str;
      };
    },

    reduceMoney() {
      if (this.userAccountMoney >= this.pay_price) {
        return this.pay_price;
      } else {
        return (this.pay_price - this.userAccountMoney).toFixed(2);
      }
    }
  },
  filters: {
    priceBeforeZero(val) {
      if (!val) return "";
      val = val.toString();
      if (val.indexOf(".") < 0) return `${val}.`;
      return val.substr(0, val.indexOf("."));
    },
    priceAfterZero(val) {
      if (!val) return "";
      val = val.toString();
      if (val.indexOf(".") < 0) return "00";
      return val.substr(val.indexOf("."), val.length);
    }
  },
  onLoad(options) {
    this.loadHandle(options);
    // #ifdef H5
    window.addEventListener("message", (msg) => {
      this.handleWebviewPostMessage(msg.data.data);
    });
    // #endif

    // #ifdef MP-ALIPAY
    let _that = this;
    my.checkBeforeAddOrder({
      success({ requireOrder, sourceId, sceneId }) {
        _that.ali = {
          ali_requireOrder: requireOrder,
          ali_sourceId: sourceId,
          ali_sceneId: sceneId
        };
      }
    });
    // #endif
  },
  onShow() {
    if (this.html) return this.$utils.toUrl(this.backUrl, "redirectTo");

    this.imgs = [
      ""
      // this.asyncImgs.images.wx_pay_icon,
      // this.asyncImgs.images.receive_pay_icon,
      // this.asyncImgs.images.account_pay_icon,
      // this.asyncImgs.images.alipay_icon,
      // this.asyncImgs.images.account_pay_icon,
    ];
  },
  methods: {
    handleWebviewPostMessage: function (data) {
      if (data?.detail?.data?.length >= 1) {
        data = data?.detail?.data[0];
      }
      if (data?.name == "postMessage" && data?.arg) {
        data = data?.arg;
      }

      if (data?.webviewMessage == "webviewClose") {
        this.outPayH5 = false;
        this.outPayH5Url = "";
        this.paySuccessCb();
      }
    },
    async loadHandle(options) {
      let data = options.data || {};
      if (data == "getStorage") {
        data = uni.getStorageSync("payParams");
      }
      data = JSON.parse(data);
      if (data.url && data.url == "adopt_pay") {
        this.adopt_pay = true;
      }
      this.pay_price = data.pay_price;
      this.realPrice = data.pay_price;
      this.pay_type_list = data.pay_type_list;
      // let index = this.pay_type_list.findIndex((item) => {
      //   return item.payment == 7;
      // });
      // if (index > -1) {
      //   this.pay_type_list.splice(index, 1);
      // }
      this.payData = data.payData;
      this.backUrl = data.backUrl;
      this.isFacePay = data.isFacePay || false;
      this.isMember = data.isMember || false; //会员充值

      // 当前user_code仅会在app跳转小程序时才有，用于登录获取token信息，参数仅可使用一次
      if (options.app_user_code) {
        this.app_user_code = options.app_user_code;
        await this.loginHandle();
      }

      if (!options.is_pt && !this.isMember) {
        const res = await this.$allrequest.order.detail({
          order_id: data.payData.order_id
            ? data.payData.order_id
            : data.payData.order_id_list[0]
        });

        // #ifdef APP-PLUS
        this.app_user_code = res.data.app_user_code;
        this.app_wx_mini_id = res.data.app_wx_mini_id;
        this.app_wx_mini_type = res.data.app_wx_mini_id_type;
        this.app_alipay_mini_id = res.data.app_alipay_mini_id;
        // #endif

        if (!res.code && res.data && res.data.activity_cut_price_order_id) {
          this.activity_cut_price_order_id = parseInt(
            res.data.activity_cut_price_order_id
          );
        }
      }

      this.getUserAccountMoney();

      // else {
      //   if (!this.isMember) {
      //     this.is_pt = options.is_pt || data.is_pt;
      //   }
      // }
      this.is_pt = options.is_pt;
      this.createDate = data.createDate;
      this.calculateTimes(data.createDate); //计算订单剩余多少秒
      if (data?.payData) {
        this.payment = data.payData.pay_type;
      }

      if (!this.activity_cut_price_order_id) {
        this.startCountDown();
      }
      setTimeout(() => {
        uni.removeStorageSync("payParams");
      }, 0);
    },
    async loginHandle() {
      return new Promise((resolve, reject) => {
        // #ifdef MP-WEIXIN
        uni.login({
          provider: "weixin",
          success: async (success) => {
            const res = await passportCode({
              code: success.code,
              app_user_code: this.app_user_code
            });

            if (res.code != 0) return;
            uni.setStorageSync("token", res.data.access_token);
            resolve();
          },
          fail: (fail) => {
            reject(fail);
          }
        });
        // #endif
        // #ifdef MP-ALIPAY
        uni.login({
          provider: "alipay",
          scopes: "auth_user",
          success: async (success) => {
            const res = await this.$allrequest.user.auth_user_auth({
              authCode: success.code,
              app_user_code: this.app_user_code
            });

            if (res.code != 0) return;
            uni.setStorageSync("token", res.data.access_token);
            resolve();
          },
          fail: (fail) => {
            reject(fail);
          }
        });
        // #endif
      });
    },
    // 计算支付时间倒计时
    calculateTimes(date) {
      let time = date * 1000 + 15 * 60 * 1000; //结束时间戳
      let currentTime = new Date().getTime(); // 当前时间戳
      currentTime = time - currentTime <= 0 ? 0 : time - currentTime;
      this.countDown = currentTime;
    },
    // 支付余额支付
    combinePay() {
      this.isCombinePay = this.isCombinePay == 0 ? 1 : 0;
      if (this.isCombinePay == 0) {
        this.realPrice = this.pay_price;
      } else {
        // 余额 >= 支付金额
        if (this.userAccountMoney - 0 >= this.pay_price - 0) {
          this.isShowViewPay = false;
          this.realPrice = 0;
          this.payment = "";
        } else {
          this.realPrice = (this.pay_price - this.userAccountMoney).toFixed(2);
        }
      }
    },
    //   获取用户余额
    getUserAccountMoney() {
      this.$allrequest.user.getUserAccountMoney().then((res) => {
        if (!res.code) {
          this.userAccountMoney = res.data.user.money;
          this.useCombinePay = res.data.is_open_combine;
          this.obj = parseFloat(
            res.data.user.money_month - res.data.user.money_month_used
          );

          //  判断如果余额的话 则优先使用余额
          if (parseFloat(this.userAccountMoney)) { 
            this.combinePay();
          }
        }
      });
    },
    // 开始倒计时
    startCountDown() {
      if (this.countDown <= 0) {
        return uni.showToast({
          title: this.$t("pay.noPay"),
          icon: "none",
          duration: 1000,
          complete() {
            setTimeout(() => {
              uni.redirectTo({
                url: "/order/order/order"
              });
            }, 1000);
          }
        });
      }
      this.timer = setInterval(() => {
        let time = this.countDown / 1000; //秒
        this.countDown = this.countDown - 1000;

        let hour = Math.floor(time / (60 * 60));
        let minute = Math.floor(time / 60) - hour * 60;
        let second = Math.floor(time) - hour * 60 * 60 - minute * 60;
        second = second < 0 ? 0 : second;
        this.hour = hour < 10 ? "0" + hour : hour;
        this.minute = minute < 10 ? "0" + minute : minute;
        this.second = second < 10 ? "0" + second : second;
        if (hour <= 0 && minute <= 0 && second <= 0) {
          clearInterval(this.timer);
          // return uni.showToast({
          //   title: "超时未支付！",
          //   icon: "none",
          //   duration: 1000,
          //   complete() {
          //     setTimeout(() => {
          //       uni.redirectTo({
          //         url: "/pages/order/order",
          //       });
          //     }, 1000);
          //   },
          // });
        }
      }, 1000);
    },
    // 切换支付类型
    handlePayTypeItem(item) {
      // 剩余支付为0  取消组合支付
      if (this.realPrice <= 0) {
        this.isCombinePay = 0;
      }
      this.payment = item.payment;
      this.payData.pay_type = item.payment;
    },
    // 支付
    gotoPay() {
      if (this.payment === 11) {
        this.$utils.toUrl(
          `/other/offlinePayment/index?orderId=${this.payData.order_id}`,
          "redirectTo"
        );
        return;
      }

      if (this.payment === 7) {
        this.$utils.toUrl(
          `/order/pay-another/pay-another?orderId=${this.payData.order_id}`,
          "redirectTo"
        );
        return;
      }

      // 开启组合付 && 使用组合付 && 余额有钱
      if (this.useCombinePay && this.isCombinePay && this.userAccountMoney) {
        this.payData = { is_combine: this.isCombinePay, ...this.payData };
      }

      let reqPayData = {
        _from: "mini",
        // #ifdef APP-PLUS
        _from: "app",
        // #endif
        // #ifdef H5
        _from: this.$utils.isWechat() ? "official" : "h5",
        // #endif
        ...this.payData,

        // #ifdef MP-ALIPAY
        ...this.ali
        // #endif
      };

      // 选择了adapay支付 && 当前app环境
      if (
        [101, 401].some((item) => item == this.payment) &&
        reqPayData._from == "app"
      ) {
        let pay_type_list = this.pay_type_list.filter((item) => {
          return item.payment == this.payment;
        });
        let sweixinParams = {
          type: this.app_wx_mini_type,
          id: this.app_wx_mini_id,
          path: `/other/pay/pay?data=${JSON.stringify({
            pay_price: this.pay_price,
            pay_type_list: pay_type_list,
            payData: this.payData,
            createDate: this.createDate
          })}&app_user_code=${this.app_user_code}`
        };

        // 支付宝adapay支付
        if (this.payment == 401) {
          //alipayUrl 已经有? 问号了，所以这里需要进行编码
          let query = `?data=${JSON.stringify({
            pay_price: this.pay_price,
            pay_type_list: pay_type_list,
            payData: this.payData,
            createDate: this.createDate
          })}&app_user_code=${this.app_user_code}`;

          // page=pages/index/index  跳转到支付宝小程序页面的页面路径
          let alipayUrl = `${
            uni.getSystemInfoSync().platform == "ios" ? "alipay" : "alipays"
          }://platformapi/startapp?appId=${
            this.app_alipay_mini_id
          }&page=other/pay/pay${encodeURIComponent(query)}`;

          //唤起支付宝
          plus.runtime.openURL(alipayUrl);
          setTimeout(() => {
            uni.showModal({
              title: "提示",
              content: "是否已支付成功",
              cancelText: "未支付",
              cancelColor: "#000000",
              confirmText: "已支付",
              confirmColor: "#3CC51F",
              success: (result) => {
                let status = 0;
                if (result.confirm) {
                  status = 1;
                } else {
                  status = 0;
                }
                this.$utils.toUrl(
                  "/order/order/order?status=" + status,
                  "redirectTo"
                );
              }
            });
          }, 1000);
        }
        // 微信adapay支付
        if (this.payment == 101) {
          plus.share.getServices((res) => {
            let serve = res.find((item) => item.id == "weixin");
            if (!serve) return uni.$u.toast(`未检测到微信APP`);
            // 唤醒小程序

            serve.launchMiniProgram(sweixinParams);

            setTimeout(() => {
              uni.showModal({
                title: "提示",
                content: "是否已支付成功",
                cancelText: "未支付",
                cancelColor: "#000000",
                confirmText: "已支付",
                confirmColor: "#3CC51F",
                success: (result) => {
                  let status = 0;
                  if (result.confirm) {
                    status = 1;
                  } else {
                    status = 0;
                  }
                  this.$utils.toUrl(
                    "/order/order/order?status=" + status,
                    "redirectTo"
                  );
                }
              });
            }, 1000);
          });
        }

        return;
      }

      // 是否会员充值
      if (this.isMember) {
        return this.memberPayOrder(reqPayData);
      }

      if (this.isFacePay) {
        this.facePayOrder(reqPayData);
        return;
      }
      uni.showLoading({
        title: this.$t("pay.pay")
      });
      if (this.adopt_pay == true) {
        adopt_order.pay_data(reqPayData).then((res) => {
          uni.hideLoading();
          orderPay.paySubmit(res, "", this.payment, () => {
            this.paySuccessCb();
          });
        });
      } else {
        let requestName = "payData";
        this.is_pt && (requestName = "ptPayData");

        this.$allrequest.order[requestName](reqPayData)
          .then((res) => {
            uni.hideLoading();
            if (res.code == 0) {
              // 月付
              if (this.payment === 12) {
                uni.showToast({
                  title: res.msg,
                  duration: 2000
                });
                this.$utils.toUrl("/order/order/order?status=1", "redirectTo");

                return;
              }
            } else {
              uni.showToast({
                title: res.msg,
                icon: "error",
                duration: 2000
              });
            }
            // #ifdef H5
            if (reqPayData.pay_type == 4 && res.data) {
              this.html = res.data;
              this.$nextTick(() => {
                document.getElementById("alipay_submit").submit();
              });
              return;
            }
            // #endif

            orderPay.paySubmit(res, "", this.payment, (res) => {
              if (this.payment == 1001) {
                this.outPayH5 = true;
                this.outPayH5Url = res.data.data.form_url;

                // setTimeout(()=>{
                //   this.outPayH5Url = 'http://192.168.0.159:8080/h5/static/h5/webview.html';
                // }, 5000);

                return;
              }
              // #ifdef H5
              if (!this.$utils.isWechat()) {
                return (this.showPayResult = true);
              }
              // #endif
              this.paySuccessCb(res);
            });
          })
          .catch((err) => {
            this.$utils.toast(err.msg || "发生未知错误");
            // // #ifdef H5
            // if (this.$utils.isWechat()) {
            //   if (!err.wechat_platform_open_id) {
            //     let pages = getCurrentPages();
            //     uni.setStorageSync(
            //       "pagesUrl",
            //       pages[pages.length - 1].__page__.fullPath
            //     );
            //     window.location.href = err.h5_auth_link;
            //   }
            // }
            // // #endif
          });
      }
    },

    // 提交支付
    async facePayOrder(params) {
      uni.showLoading({
        title: this.$t("pay.pay")
      });
      try {
        uni.showLoading({
          title: this.$t("pay.pay")
        });
        const res = await this.$allrequest.facePay.payOrder(params);
        uni.hideLoading();
        if (res.code != 0) return this.errorNotice(res);
        this.paySubmit(res, params.pay_type);
      } catch (error) {
        uni.hideLoading();
      }
    },

    // 会员订单提交
    async memberPayOrder(params) {
      try {
        uni.showLoading({
          title: this.$t("pay.pay")
        });
        const res = await this.$allrequest.facePay.memberPayOrder(params);
        uni.hideLoading();
        if (res.code != 0) return this.errorNotice(res);
        this.paySubmit(res, params.pay_type);
      } catch (error) {
        uni.hideLoading();
      }
    },

    // 支付操作
    paySubmit(payData, pay_type = 0) {
      // 已经支付成功
      if (!payData.data) {
        uni.showToast({
          title: payData.msg,
          icon: "none",
          duration: 2000
        });
        setTimeout(() => {
          this.$utils.toUrl(this.backUrl, "redirectTo");
        }, 2000);
        return;
      } else {
        const that = this;
        uni.getProvider({
          service: "payment",
          success: (res) => {
            // 微信
            if (
              res.provider.indexOf("wxpay") > -1 &&
              (pay_type == 1 || pay_type == 13)
            ) {
              // #ifdef MP-WEIXIN
              uni.requestPayment({
                provider: "wxpay",
                orderInfo: payData.res,
                timeStamp: payData.data.timeStamp,
                nonceStr: payData.data.nonceStr,
                package: payData.data.package,
                signType: payData.data.signType,
                paySign: payData.data.paySign,
                success: (res) => {},
                complete: (res) => {
                  if (
                    "requestPayment:fail" != res.errMsg &&
                    "requestPayment:fail cancel" != res.errMsg
                  ) {
                    // 支付成功回调
                    this.paySuccessCb();
                  } else {
                    uni.showToast({
                      title: this.$t("order.payFail"),
                      icon: "none",
                      duration: 2000
                    });
                  }
                }
              });
              // #endif

              // #ifdef APP-PLUS
              uni.requestPayment({
                provider: "wxpay",
                orderInfo: {
                  appid: payData.data.appid, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
                  noncestr: payData.data.noncestr, // 随机字符串
                  package: payData.data.package, // 固定值
                  partnerid: payData.data.partnerid, // 微信支付商户号
                  prepayid: payData.data.prepayid, // 统一下单订单号
                  timestamp: payData.data.timestamp, // 时间戳（单位：秒）
                  sign: payData.data.sign // 签名，这里用的 MD5 签名
                },
                success: (res) => {},
                complete: (res) => {
                  if (res.errMsg.indexOf("requestPayment:fail") == -1) {
                    // 支付成功回调
                    this.paySuccessCb();
                  } else {
                    uni.showToast({
                      title: this.$t("order.payFail"),
                      icon: "none",
                      duration: 2000
                    });
                  }
                }
              });
              // #endif
            }

            // 支付宝
            if (res.provider.indexOf("alipay") > -1 && pay_type == 4) {
              uni.requestPayment({
                provider: "alipay",
                orderInfo: payData.data,
                success: (res) => {
                  if (res.errMsg.indexOf("requestPayment:fail") == -1) {
                    // 支付成功回调
                    this.paySuccessCb();
                  } else {
                    uni.showToast({
                      title: this.$t("order.notPay"),
                      icon: "none",
                      duration: 2000
                    });
                  }
                },
                fail: () => {
                  uni.showToast({
                    title: this.$t("order.notPay"),
                    icon: "none",
                    duration: 2000
                  });
                  setTimeout(() => {
                    uni.navigateBack();
                  }, 1500);
                }
              });
            }

            // 头条
            if (res.provider.indexOf("toutiao") > -1 && pay_type == 5) {
              uni.requestPayment({
                provider: "toutiao",
                orderInfo: payData.data,
                service: 5,
                success: (res) => {
                  if (typeof res.errMsg != "undefined") {
                    uni.showToast({
                      title: this.$t("order.notPay"),
                      icon: "none",
                      duration: 2000
                    });
                  }
                  if (typeof res.code != "undefined") {
                    if (res.code == 0) {
                      this.paySuccessCb();
                    } else {
                      uni.showToast({
                        title: this.$t("order.notPay"),
                        icon: "none",
                        duration: 2000
                      });
                    }
                  }
                },
                complete: (res) => {}
              });
            }
          }
        });
      }
    },

    async getCardList(fn) {
      let res = await this.$allrequest.order.detail({
        order_id: this.payData.order_id
          ? this.payData.order_id
          : this.payData.order_id_list[0]
      });

      if (res.code == 0 && res.data && parseInt(res.data.is_pay) === 1) {
        if (
          (res.data.verify_card && res.data.verify_card.length) ||
          (res.data.coupon_card && res.data.coupon_card.length)
        ) {
          this.verify_card = res.data.verify_card;
          this.coupon_card = res.data.coupon_card;
          this.showVirtualPop = true;
          return;
        }
      }

      fn();
    },

    // 支付成功回调
    paySuccessCb(status = 1) {
      // 只有app打开小程序才有这个参数
      // #ifdef MP-ALIPAY || MP-WEIXIN
      if (this.$mp.query.app_user_code) {
        this.showBackApp = true;
        return;
      }
      // #endif

      if (status) {
        uni.showToast({
          title: this.$t("order.paySuc"),
          icon: "none",
          duration: 2000
        });
      }

      if (this.isMember) {
        uni.navigateBack();
        return;
      }
      if (this.is_pt) return this.payBtn();
      // this.$allrequest.order.paySuccess({ order_id: this.payData.order_id });
      this.getCardList(() => {
        setTimeout(() => {
          if (this.backUrl) {
            let type = "redirectTo";
            if (this.backUrl === "/pages/home/home") type = "switchtab";
            this.$utils.toUrl(this.backUrl, type);
          } else {
            uni.navigateBack();
          }
        }, 1500);
      }).catch((err) => {});
    },

    // 错误提示
    errorNotice(res) {
      uni.hideLoading();
      uni.showToast({
        title: res.msg,
        icon: "none",
        duration: 2000
      });
    },
    // 点击支付结果按钮
    payBtn() {
      this.showPayResult = false;
      if (this.is_pt) return this.$utils.toUrl("/pt/order/index", "redirectTo");
      this.$utils.toUrl("/order/order/order", "redirectTo");
    },

    goCardList() {
      if (this.verify_card.length) {
        let { verify_card } = this,
          type = parseInt(verify_card[0].type);

        uni.redirectTo({
          url: `/user/write_off_card/write_off_card?type=${type}`
        });
      } else {
        uni.redirectTo({
          url: `/user/my_coupon/my_coupon`
        });
      }
    }
  },
  onUnload() {
    if (this.timer) clearInterval(this.timer);
  }
};
</script>

<style lang="scss" scoped>
.pay-settle-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f2f2f2;
  font-family: PingFang SC;
  padding-bottom: calc(99rpx + env(safe-area-inset-bottom));

  .page-header {
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 50rpx 0 30rpx 0;

    .pay-price {
      font-size: 80rpx;
      display: flex;
      font-weight: bold;
      justify-content: center;
      align-items: flex-end;
      height: 112rpx;
      text:first-child {
        font-size: 48rpx;
        line-height: 80rpx;
      }
    }

    .pay-rest-time {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24rpx;
      color: #8c8c8c;
    }
  }

  .page-body {
    width: 100%;

    .recommend-pay {
      width: 100%;
      background: #ffffff;
      margin-bottom: 24rpx;

      .recommend-pay-name {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 37rpx;
        line-height: 100rpx;
        font-size: 28rpx;
        font-weight: 400;
        color: #888888;

        view:first-child {
          font-size: 32rpx;
          font-weight: 600;
          color: #262626;
        }
      }

      .recommend-pay-detail {
        padding: 32rpx 37rpx 40rpx;
        border-top: 1px solid #f2f2f2;
        .select {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .pay-detail {
            display: flex;

            image {
              width: 48rpx;
              height: 48rpx;
              display: block;
              margin-right: 22rpx;
            }

            .pay-word {
              font-size: 28rpx;
              font-weight: 400;
              color: #262626;
              line-height: 44rpx;

              text:last-child {
                color: #888888;
              }
            }
          }

          .is-select {
            view {
              width: 40rpx;
              height: 40rpx;
              background: #ffffff;
              border: 3rpx solid #8c8c8c;
              border-radius: 50%;
            }

            image {
              width: 40rpx;
              height: 40rpx;
            }
          }
        }
      }
    }

    .pay-way-list {
      width: 100%;
      background: #ffffff;
      > view:nth-child(1) {
        line-height: 98rpx;
        padding: 0 37rpx;
        .left {
          font-size: 32rpx;
          font-weight: 600;
          color: #262626;
        }
        .right {
          font-size: 26rpx;
          color: #f7271f;
        }
      }

      .pay-way-item {
        border-top: 1px solid #f2f2f2;
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0rpx 37rpx;
        height: 120rpx;
        position: relative;

        .pay-type {
          display: flex;
          align-items: center;
          font-size: 28rpx;
          font-weight: 400;
          color: #262626;
          line-height: 44rpx;

          image {
            width: 44rpx;
            height: 44rpx;
            display: block;
            // margin-right: 24rpx;
          }

          text {
            margin-left: 14rpx;
          }
        }

        .is-select {
          view {
            width: 40rpx;
            height: 40rpx;
            background: #ffffff;
            border: 3rpx solid #8c8c8c;
            border-radius: 50%;
          }

          image {
            width: 40rpx;
            height: 40rpx;
            display: block;
          }
        }
      }

      .pay-way-item::after {
        content: "";
        width: 640rpx;
        height: 1rpx;
        background: #f2f2f2;
        position: absolute;
        right: 0;
        bottom: 0;
        z-index: 11;
      }
    }
  }

  .page-foot {
    width: 100%;
    height: calc(99rpx + env(safe-area-inset-bottom));
    background: #ffffff;
    box-shadow: 0 -1rpx 0 0 #f2f2f2;
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 111;

    .pay-btn {
      margin: 15rpx auto 0;
      width: 678rpx;
      height: 76rpx;
      background: linear-gradient(90deg, #ff4e18, #f32524);
      border-radius: 38rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 30rpx;
      font-weight: 500;
      color: #ffffff;
    }
  }
}
.payResBox {
  position: fixed;
  width: 100%;
  height: 100vh;
  top: 0;
  left: 0;
  z-index: 10000;
  background-color: rgba(0, 0, 0, 0.5);
}
.payRes {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 300rpx 40rpx 0 40rpx;
  button {
    width: 100%;
  }
}

/* 新增弹框 */
.virtualPop {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 76rpx;
  background: rgba(0, 0, 0, 0.5);
}

.virtualPopBox {
  position: relative;
  width: 100%;

  .hd {
    image {
      width: 100%;
      display: block;
    }
  }

  .conBox {
    padding: 30rpx 36rpx 0;
    background: #f2302d;
    border-radius: 0px 0px 24rpx 24rpx;
    box-sizing: border-box;
    overflow: hidden;

    .scroll {
      max-height: 450rpx;
      overflow-y: auto;
    }
  }

  .btn {
    padding: 48rpx 42rpx;

    view {
      background: #ffce45;
      border-radius: 32px;
      text-align: center;
      height: 76rpx;
      line-height: 76rpx;
      font-size: 32rpx;
      color: #f0250e;
    }
  }
}

.cardItem {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: #fdf0f0;
  border: 2rpx solid #fdd6d0;
  border-radius: 20rpx;

  .img {
    overflow: hidden;
    margin-right: 20rpx;
    width: 92rpx;
    height: 92rpx;
    background: #fff;
    border-radius: 10px;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .txt {
    flex: 1;
    overflow: hidden;
    color: #f0250e;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .con {
      flex: 1;
      overflow: hidden;
    }

    .btn {
      width: 140rpx;
      height: 55rpx;
      line-height: 55rpx;
      border-radius: 32px;
      color: #fff;
      background: #f0250e;
      text-align: center;
      font-size: 24rpx;
    }

    .name,
    .num {
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }

    .name {
      font-size: 32rpx;
      font-weight: bold;
    }

    .num {
      padding-top: 8rpx;
      font-size: 22rpx;
    }
  }
}

.couponItem {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24rpx;
  padding: 10rpx 24rpx;
  min-height: 132rpx;
  background: #fdf0f0;
  border-radius: 20rpx;

  .line {
    position: absolute;
    left: -10rpx;
    right: -10rpx;
    top: 50%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: -12rpx;

    view {
      width: 24rpx;
      height: 24rpx;
      background: #f2302d;
      border-radius: 32px;
    }
  }

  .let {
    flex: 1;
    overflow: hidden;
    margin-right: 10rpx;
  }

  .title {
    padding-bottom: 10rpx;
    font-size: 30rpx;
    color: #262626;
    font-weight: bold;
  }

  .time,
  .text {
    font-size: 22rpx;
    color: #8c8c8c;
  }

  .price {
    display: flex;
    align-items: flex-end;
    justify-content: center;
    font-size: 48rpx;
    color: #f0250e;
    font-weight: bold;
    line-height: 1;
    flex: 1;
    overflow: hidden;

    &.s1:before {
      content: "¥";
      font-size: 28rpx;
      padding-bottom: 4rpx;
    }

    &.s2:after {
      content: "折";
      font-size: 28rpx;
      padding-bottom: 4rpx;
    }
  }
}

.back-app-popup-box {
  padding-top: 20rpx;
  padding-bottom: 30rpx;
  width: 60vw;
  background: #fff;

  .back-app {
    padding: 10rpx 20rpx;
    border-radius: 10rpx;
    color: #3cc51f;
  }
}
</style>
